﻿using System.Text;
using Basic.WxApiService.Interface;
using Basic.WxApiService.WxModel;
using WeDonekRpc.Helper;
using WeDonekRpc.Helper.Http;

namespace Basic.WxApiService.PlatformApi
{
    internal class WxPlatformBase
    {
        public static Result Get<Result> (string uri, IComponentToken comToken, string query) where Result : WxBasicRes
        {
            Uri apiUri = query == null ? new Uri(string.Format("{0}?component_access_token={1}&component_appid={2}", uri, comToken.Token, comToken.AppId)) : new Uri(string.Format("{0}?component_access_token={1}&component_appid={2}&{3}", uri, comToken.Token, comToken.AppId, query));
            Result result = HttpHelper.Get<Result>(apiUri);
            if (result.errcode == 0)
            {
                return result;
            }
            else if (result.errcode == 42001)
            {
                comToken.ResetToken();
                return Get<Result>(uri, comToken, query);
            }
            throw new ErrorException(string.Concat("wx.platform.api.", result.errcode));
        }
        public static Result Get<Result> (Uri uri) where Result : WxBasicRes
        {
            Result result = HttpHelper.Get<Result>(uri);
            if (result.errcode == 0)
            {
                return result;
            }
            throw new ErrorException(string.Concat("wx.platform.api.", result.errcode));
        }
        public static Result PostJson<Result> (Uri uri, StringBuilder json) where Result : WxBasicRes
        {
            Result result = HttpHelper.PostJson<Result>(uri, json.ToString());
            if (result.errcode == 0)
            {
                return result;
            }
            throw new ErrorException(string.Concat("wx.platform.api.", result.errcode));
        }
        public static Result PostJson<Result> (string uri, IComponentToken comToken, string json) where Result : WxBasicRes
        {
            Uri apiUri = new Uri(string.Format("{0}?component_access_token={1}", uri, comToken.Token));
            Result result = HttpHelper.PostJson<Result>(apiUri, json);
            if (result.errcode == 0)
            {
                return result;
            }
            else if (result.errcode == 42001)
            {
                comToken.ResetToken();
                return PostJson<Result>(uri, comToken, json);
            }
            throw new ErrorException(string.Concat("wx.platform.api.", result.errcode));
        }
    }
}
